# -*- coding: utf-8 -*-
from flask import Blueprint, g
from common.response import success, error
from common.error_code import ErrorCode
from common.token import generate_token
from dao.db import db
from dao.user_dao import Teacher, User, get_user_by_username, verify_password
from filter.auth import auth_required
from filter.decorators import require_role, validate_request
from model.request import ChangePasswordKeyRequest, LoginRequest, ChangePasswordRequest, ResetStudentPasswordRequest, ForgotPasswordRequest

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
@validate_request(LoginRequest)
def login():
    """用户登录接口"""
    login_data: LoginRequest = g.request_data
    
    # 查询用户
    if len(login_data.username) == 0:
        return error(ErrorCode.USER_NOT_FOUND, "用户不存在")
    user = get_user_by_username(login_data.username)
    if not user:
        return error(ErrorCode.USER_NOT_FOUND, "用户不存在")
        
    # 验证密码
    if not verify_password(user, login_data.password):
        return error(ErrorCode.PASSWORD_ERROR, "密码错误")
        
    # 构建payload
    payload = {
        'user_id': user.id,
        'role': user.role,
        'name': user.name,
        'class_id': None,
        'teacher_position': None,
        'student_id': None
    }
    
    # 根据角色添加额外信息
    if user.role == 'student' and user.student_info:
        payload['class_id'] = user.student_info.class_id
        payload['student_id'] = user.student_info.student_id
    elif user.role == 'teacher' and user.teacher_info:
        payload['class_id'] = user.teacher_info.class_id
        payload['teacher_position'] = user.teacher_info.position
        
    # 生成token
    token = generate_token(payload)
    
    return success({'token': token})

def is_password_strong(password):
    """简单的密码强度检查（可自定义）"""
    if len(password) < 6:
        return False
    # 可添加更多规则，比如必须包含字母和数字
    return True

@auth_bp.route('/change-password', methods=['POST'])
@auth_required
@validate_request(ChangePasswordRequest)
def change_password():
    """修改自己的密码"""
    data = g.request_data

    # 1. 获取当前用户信息
    user = User.query.get(g.user_id)
    if not user:
        return error(ErrorCode.NOT_FOUND, "用户不存在")

    # 2. 验证旧密码
    if user.password != data.old_password:
        return error(ErrorCode.INVALID_PARAM, "旧密码错误")

    # 3. 验证新密码强度
    if not is_password_strong(data.new_password):
        return error(ErrorCode.INVALID_PARAM, "新密码强度不够 (至少6位)")

    # 4. 更新密码
    user.password = data.new_password
    db.session.commit()

    return success("密码修改成功")

@auth_bp.route('/reset-student-password', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(ResetStudentPasswordRequest)
def reset_student_password():
    """管理员或老师修改学生密码"""
    data = g.request_data

    # 1. 验证管理员/教师口令
    # admin/teacher 的口令存储在 Teacher.password_hash
    teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员/教师口令错误")

    # 2. 查找学生
    student_user = User.query.filter_by(id=data.student_id, role='student').first()
    if not student_user:
        return error(ErrorCode.NOT_FOUND, "学生不存在")

    # 3. 验证新密码强度
    if not is_password_strong(data.new_password):
        return error(ErrorCode.INVALID_PARAM, "新密码强度不够 (至少6位)")

    # 4. 更新密码
    student_user.password = data.new_password
    db.session.commit()

    return success("学生密码修改成功")

@auth_bp.route('/forgot-password', methods=['POST'])
@validate_request(ForgotPasswordRequest)
def forgot_password():
    """管理员/教师忘记密码，通过口令重置自己的密码"""
    data = g.request_data

    # 1. 通过口令确认教师或管理员身份
    teacher = Teacher.query.filter_by(password_hash=data.admin_password).first()
    if not teacher:
        return error(ErrorCode.FORBIDDEN, "验证口令失败")

    # 2. 验证新密码强度
    if not is_password_strong(data.new_password):
        return error(ErrorCode.INVALID_PARAM, "新密码强度不够（至少6位）")

    # 3. 更新密码
    user = User.query.get(teacher.user_id)
    if not user:
        return error(ErrorCode.NOT_FOUND, "用户不存在")

    user.password = data.new_password
    db.session.commit()

    return success("密码重置成功")

@auth_bp.route('/change-password-key', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(ChangePasswordKeyRequest)
def change_password_key():
    """修改教师或管理员口令"""
    params = g.request_data
    current_user_id = g.user_id
    
    # 1. 获取当前用户信息
    user = User.query.get(current_user_id)
    if not user:
        return error(ErrorCode.NOT_FOUND, "用户信息不存在")
    
    # 2. 验证登录密码
    if user.password != params.login_password:
        return error(ErrorCode.INVALID_PARAM, "登录密码不正确")
    
    # 3. 验证旧口令
    teacher = Teacher.query.filter_by(user_id=current_user_id).first()
    if not teacher:
        return error(ErrorCode.NOT_FOUND, "教师信息不存在")
    # 验证旧口令
    if teacher.password_hash != params.old_password_key:
        return error(ErrorCode.INVALID_PARAM, "旧口令不正确")
    target = teacher
    password_key_field = 'password_hash'
        
    
    # 4. 检查新口令复杂度（可根据实际需求调整）
    if len(params.new_password_key) < 6:
        return error(ErrorCode.INVALID_PARAM, "新口令长度不能少于6位")
    
    # 5. 更新新口令（加密存储）
    setattr(target, password_key_field, params.new_password_key)
    db.session.commit()
    
    return success("口令修改成功")